package edu.hunau.recommend.advice;

import edu.hunau.recommend.common.R;
import edu.hunau.recommend.common.ResultCodeEnum;
import edu.hunau.recommend.controller.admin.AdminManagerController;
import edu.hunau.recommend.exception.RecommendBusinessException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Result;
import java.lang.reflect.Method;
import java.util.Objects;


/**
 * 配置切入点
 * @author name
 * @creater 2022-09-14-10:11
 */
@Aspect
@Configuration
public class ControllerAspect {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    @Around("execution(* edu.hunau.recommend.controller.admin.*.*(..))" +
            "&& @annotation(org.springframework.web.bind.annotation.RequestMapping)")

    public Object adminControllerBeforeValedation(ProceedingJoinPoint joinPoint)throws Throwable{
        //获得方法签名
        Method targetMethod = ((MethodSignature) joinPoint.getSignature()).getMethod();
        //是否存在AdminPermission的注解
        AdminPermission adminPermission = targetMethod.getAnnotation(AdminPermission.class);
        if(Objects.isNull(adminPermission)){
            //执行目标方法
            Object result = joinPoint.proceed();
            return result;
        }
        //需要进行权限校验: 判断session中是否存储值
        Object email = request.getSession().getAttribute(AdminManagerController.ADMIN_NAME_SESSION);
        //如果没有登录
        if(Objects.isNull(email)){
            if ("text/html".equals(adminPermission.produceType())){
                //跳转到登录界面
                response.sendRedirect("/admin/admin/loginPage");
                return null;
            }else {

                RecommendBusinessException ex = new RecommendBusinessException(ResultCodeEnum.ADMIN_SHOULD_LOGIN);
                return R.setResult(ResultCodeEnum.ADMIN_SHOULD_LOGIN);
            }

        }else{
            //执行目标方法
            Object result = joinPoint.proceed();
            return result;
        }

    }
}
